import Fly from 'flyio/dist/npm/wx';
import Taro from '@tarojs/taro';
export default class service {
    constructor() {
        this.paramsSerializer = params => {
            const parts = [];
            for (let key in params) {
                let val = params[key];

                if (val === null || Object.prototype.toString.call(val) === '[object Undefined]') {
                    continue;
                }

                if (Array.isArray(val)) {
                    val = JSON.stringify(val);
                }

                parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
            }
            const result = parts.join('&');
            return result;
        };

        this.fly = new Fly();

        this.fly.config = {
            parseJson: true,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
            timeout: 0
        };

        this.fly.interceptors.request.use(
            config => {
                config.baseURL = config.baseURL + '/api/';

                //url过滤白名单
                const whiteList = [''];

                if (
                    whiteList.some(item => {
                        return config.url.includes(item);
                    }) === false
                ) {
                    //需要token的url在此处处理
                }

                return Promise.resolve(config);
            },
            error => Promise.reject(error)
        );

        this.fly.interceptors.response.use(
            response => {
                const { data } = response;
                return Promise.resolve(data);
            },
            error => {
                const code = parseInt(error?.response?.status, 10);

                if (code <= 600 || code >= 400) {
                    Taro.showToast({
                        title: error.message,
                        icon: 'none'
                    });
                }

                return Promise.reject(error);
            }
        );
    }
}
